﻿using System.Linq;
using System.Web;
using System.Web.Mvc;
using Inscriptionem.Localization;

namespace Inscriptionem.MVC
{
    public class BlogActionFilterAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            var language = new ORM.DB().Languages.First(l => l.Name.ToLower() == Language.Current.Value.ToLower());

            // Check section
            if (filterContext.RouteData.Values["section"] == null ||
                (filterContext.RouteData.Values["section"] != null && string.IsNullOrWhiteSpace(filterContext.RouteData.Values["section"].ToString())))
            {
                var section = language.Sections.FirstOrDefault(s => s.IsDefault);
                if (section == null)
                {
                    throw new HttpException(404, "Section not found!");
                }

                filterContext.RouteData.Values["section"] = section.Name;
            }
            else
            {
                var sectionName = filterContext.RouteData.Values["section"].ToString();

                if (!string.IsNullOrWhiteSpace(sectionName))
                {
                    var section = language.Sections.FirstOrDefault(s => s.Name.ToLower() == sectionName.ToLower());
                    if (section == null)
                    {
                        throw new HttpException(404, "Section not found!");
                    }
                }
            }

            base.OnActionExecuting(filterContext);
        }

        public override void OnResultExecuted(ResultExecutedContext filterContext)
        {
            if (filterContext.Result is HttpNotFoundResult)
            {
                throw new HttpException(404, "Not found!");
            }

            base.OnResultExecuted(filterContext);
        }
    }
}